import { IProductDetail } from "../../typings";
import { IModalBundleGroups, IModalBundles, IModalProductCategory, IModalProducts } from "../../typings/types/cloud-models";

// 初始化数据模型客户端
const models = wx.cloud.models;

const getProductDetail = async (id: string, isBundle: boolean) => {

  const specGroups = (await models.specGroups.list({
    filter: {
      where: {
        productIds: {
          $in: [id]
        }
      }
    }
  })).data.records
  const specs = (await models.specs.list({
    filter: {
      where: {
        groupId: {
          $in: [...specGroups.map(i => i._id)]
        }
      }
    }
  })).data.records

  if (isBundle) {
    const bundle = (await models.bundles.get({
      filter: {
        where: {
          _id: {
            $eq: id
          }
        }
      }
    })).data
    const bundleGroups = (await models.bundleGroups.list({
      filter: {
        where: {
          bundleId: {
            $eq: bundle._id
          }
        }
      }
    })).data.records
    const bundleCategory = (await models.productCategory.get({
      filter: {
        where: {
          _id: {
            $eq: bundle.category
          }
        }
      }
    })).data
    const products = (await models.products.list({
      filter: {
        where: {
          _id: {
            $in: bundle.items.map(i => i.productId)
          }
        }
      }
    })).data.records
    const productDetail = {
      ...bundle,
      isBundle: true,
      images: undefined,
      specs: undefined,
      bundleItems: bundleGroups.map(group => ({
        ...group,
        items: products.map(i => ({
          ...i,
          isSelected: false,
        })),
      })),
      category: bundleCategory.name,
      categoryId: bundleCategory._id,
    } as IProductDetail
    // console.log(productDetail)
    return productDetail;
  }
  else {
    const product = (await models.products.get({
      filter: {
        where: {
          _id: {
            $eq: id
          }
        }
      }
    })).data
    const productCategory = (await models.productCategory.get({
      filter: {
        where: {
          _id: {
            $eq: product.category
          }
        }
      }
    })).data
    const productDetail = {
      ...product,
      specs: [
        ...specGroups.map(group => ({
          ...group,
          items: [
            ...specs.map(item => {
              if (item.groupId === group._id) {
                return ({
                  ...item
                })
              }
              return undefined
            })
          ].filter(j => j !== undefined)
        }))
      ].filter(i => i !== undefined),
      category: productCategory.name,
      categoryId: productCategory._id,
    } as IProductDetail
    // console.log(productDetail)
    return productDetail;
  }
}

export {
  getProductDetail
}